package taa.controller;

import com.taa.entity.Cart;
import com.taa.entity.User;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: taa
 * @Desc: 消费端控制层
 * @Create: 2025-06-14 15:38
 **/
@RestController
@RequestMapping("/consumer")
public class UserConsumerController {

    @Resource
    private DiscoveryClient discoveryClient;

    private final RestTemplate restTemplate = new RestTemplate();

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        if (instances.isEmpty()) {
            throw new RuntimeException("No provider-service available!");
        }
        
        String providerUrl = instances.get(0).getUri() + "/provider/user/" + id;

        // 3. 调用 provider-service
        return restTemplate.getForObject(providerUrl, User.class);
    }
    
}

